package com.system.permissiondemo.service.impl;

import com.google.common.base.Preconditions;
import com.system.permissiondemo.common.RequestHolder;
import com.system.permissiondemo.entity.SysDept;
import com.system.permissiondemo.exception.CustomizeException;
import com.system.permissiondemo.mapper.SysDeptMapper;
import com.system.permissiondemo.param.DeptParam;
import com.system.permissiondemo.service.SysDeptService;
import com.system.permissiondemo.util.LevelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 部门新增
     * @param deptParam
     */
    @Override
    public void save(DeptParam deptParam) {

        //校验
        if (checkExist(deptParam.getId(),deptParam.getParentId(),deptParam.getName())){
            throw new CustomizeException("同一层级下存在相同名称的部门");
        }
        SysDept dept = SysDept.builder().name(deptParam.getName())
                                        .parentId(deptParam.getParentId())
                                        .seq(deptParam.getSeq())
                                        .remark(deptParam.getRemark()).build();
        String parentLevel= getLevel(deptParam.getParentId());
        dept.setLevel(LevelUtil.calculateLevel(parentLevel,deptParam.getParentId()));
        dept.setOperator(RequestHolder.getCurrentUser().getUsername());// TODO
        dept.setOperatorIp(RequestHolder.getCurrentRequest().getRemoteAddr());// TODO
        dept.setOperatorTime(new Date());
        sysDeptMapper.insertSelective(dept);
    }

    /**
     * 部门更新
     * @param deptParam
     */
    @Override
    public void update(DeptParam deptParam) {
        //校验
        if (checkExist(deptParam.getId(),deptParam.getParentId(),deptParam.getName())){
            throw new CustomizeException("同一层级下存在相同名称的部门");
        }
        SysDept before = sysDeptMapper.selectByPrimaryKey(deptParam.getId());
        Preconditions.checkNotNull(before,"待更新的部门不存在");
        if (checkExist(deptParam.getId(),deptParam.getParentId(),deptParam.getName())){
            throw new CustomizeException("同一层级下存在相同名称的部门");
        }
        SysDept after = SysDept.builder().id(deptParam.getId())
                                         .name(deptParam.getName())
                                         .parentId(deptParam.getParentId())
                                         .seq(deptParam.getSeq())
                                         .remark(deptParam.getRemark()).build();
        String parentLevel= getLevel(deptParam.getParentId());
        after.setLevel(LevelUtil.calculateLevel(parentLevel,deptParam.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());// TODO
        after.setOperatorIp(RequestHolder.getCurrentRequest().getRemoteAddr());// TODO
        after.setOperatorTime(new Date());
        updateWithChild(before,after);
    }

    /**
     * 部门更新前后变化
     * @param before
     * @param after
     */
    @Transactional
    public void updateWithChild(SysDept before, SysDept after){
        //判断是否需要更新子部门
        String newLevelPrefix = after.getLevel();
        String oldLevelPrefix = before.getLevel();
        //不一致的时候
        if (!after.getLevel().equals(before.getLevel())){
            List<SysDept> deptList = sysDeptMapper.getChildDeptListByLevel(before.getLevel());
            if (!CollectionUtils.isEmpty(deptList)){
                for (SysDept dept:deptList){
                  String level = dept.getLevel();
                  if (level.indexOf(oldLevelPrefix)==0){
                      level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                      dept.setLevel(level);
                  }
                }
                sysDeptMapper.batchUpdateLevel(deptList);
            }
        }
        sysDeptMapper.updateByPrimaryKey(after);
    }

    /**
     * 检查数据是否已存在：部门id，部门名称，上级部门id
     * @param deptId
     * @param parentId
     * @param deptName
     * @return
     */
    private boolean checkExist(Integer deptId,Integer parentId,String deptName ){
        return sysDeptMapper.countByNameAndParentId(deptId,parentId,deptName) > 0;
    }

    /**
     * 根据部门id获取上一级部门id
     * @param deptId
     * @return
     */
    private String getLevel(Integer deptId){
        SysDept dept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (dept == null){
            return null;
        }
        return dept.getLevel();
    }
}
